#!/bin/rc
# restore arena# [dev] - load venti with arenas on dev, stored one per track
#	starting with arena#.  must have run fmtarenas before restoring
#	the first arena in the partition.
#	this must be run on the venti server, without venti running on the
#	affected arena partition(s).
rfork ne
if (test -e /sys/lib/backup/funcs)
	.   /sys/lib/backup/funcs
switch ($#*) {
case 1
case 2
	rdev=$2
case *
	echo usage: $0 arena-num '[dev]' >[1=2]
	exit usage
}
starena=$1
if (! ~ $starena [0-9] [0-9][0-9] [0-9][0-9][0-9]) {
	echo $0: bad starting arena: $starena >[1=2]
	exit bad-arena-num
}

# clear any dregs from a previous run
unmount /mnt/cd >[2]/dev/null
sleep 1
kill cdfs | rc
sleep 1
cdfs -d $rdev || exit
cd /mnt/cd

#for (track in d[0-9]*)
#	venti/wrarena $track	# slow; takes about 12½ mins. per GB

arena = $starena
# set arenabase for arenastart
arenabase = `{ venti/printarenapart $arenas | sed -e 's/.*arenabase=//' -e 1q }
kill printarenapart | rc		# printarenapart leaves a process behind
# echo arenabase $arenabase

skipping=yes
for (track in d[0-9]*) {
	if (~ track 'd[0-9]*') {
		echo $0: no tracks in /mnt/cd >[1=2]
		exit no-tracks
	}
	if (~ $skipping yes) {
		# verify that first track is the expected one
		type=`{file $track}
		switch ($"type) {
		case *': venti arena'
			name=`{ venti/printarena $track >[2=1] |
				sed -e 's/.*name=([^ =]+).*/\1/' -e 1q }
		case *
			name=NOT-A-VENTI-ARENA
		}
		kill printarena | rc	# printarena leaves a process behind

		echo -n first track is $"name'; is that right? '
		switch (`{read}) {
		case [yY]*
			skipping=no
		case skip
			skipping=yes
		case *
			echo aborting, arena is unchanged. >[1=2]
			exit 'wrong track'
		}
	}

	if (! ~ $skipping yes) {
		# copy each track into its slot in the arena partition
		venti/printarena $track >[2=1] | sed 1q | tr -d '\12'
		kill printarena | rc	# printarena leaves a process behind
	
		off = `{arenastart $arena}
		# echo -n writing $track to $arenas at 8K-block offset $off:
		sleep 3
		echo
		# argh!  something (cdfs?) appends 60K of *stuff* to each
		# arena on optical disc.  restrain dd.
		count=`{ echo $arenasize/$blocksize | bc }
		pump -i 1048576 -o 65536 -d 10 <$track |
			dd -quiet 1 -count $count -bs $blocksize -of $arenas \
				-oseek $off
		arena = `{hoc -e $arena+1}
	}
}
# when all done, must run venti/checkarenas, fmtisect, fmtbloom, fmtindex,
# and (the big one) venti/buildindex -b /cfg/pie/venti.conf
